<?php

declare(strict_types=1);

namespace App\CustHub\Listener;

use App\CustHub\Constants\ContactBehaviorTypeConstants;
use App\CustHub\Event\ContactOperationBehaviorAfter;
use App\CustHub\Model\ChContactBehaviorLog;
use App\CustHub\Model\ChCorpTag;
use App\CustHub\Model\ChSmartTag;
use Carbon\Carbon;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerInterface;

#[Listener]
class ContactOperationBehaviorListener implements ListenerInterface
{

    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            ContactOperationBehaviorAfter::class,
        ];
    }

    public function process(object $event): void
    {
        $contactId = $event->contactId;
        $extra = $event->extra;
        switch ($event->type){
            case ContactBehaviorTypeConstants::CHANGE_TAG:
                $this->changeTag($contactId,$extra);
                break;
            case ContactBehaviorTypeConstants::OTHER:
                ChContactBehaviorLog::create([
                    'contact_id' => $contactId,
                    'remark' => $extra['remark'],
                    'type' => ContactBehaviorTypeConstants::OTHER,
                    'created_at' => Carbon::now()->toDateTimeString(),
                ]);
                break;
        }
    }


    /**
     * 标签变更
     * @param mixed $contactId
     * @param array $extra
     * @return void
     */
    private function changeTag(mixed $contactId,array $extra): void
    {

        $tagIds = $extra['tagIds'] ?? [];
        $isCorpTag = $extra['isCorpTags'] ?? false;
        $isAdd = $extra['isAdd'] ?? true;
        $now = Carbon::now()->toDateTimeString();

        $prefix = $isAdd ? '新增' : '删除';

        $prefix = $isCorpTag ? $prefix.'企微标签' : $prefix.'智能标签';

        $logData = [];
        if($isCorpTag){
            //企微标签
            $tagNames = ChCorpTag::query()
                ->whereIn('id',$tagIds)
                ->pluck('name')
                ->map(function ($item){
                    return "【{$item}】";
                })->implode('、');
        }else{
            //智能标签
            $tagNames = ChSmartTag::query()
                ->whereIn('id',$tagIds)
                ->pluck('name')
                ->map(function ($item){
                    return "【{$item}】";
                })->implode('、');
        }

        foreach ($contactId as $item){
            $logData[] = [
                'contact_id' => $item,
                'remark' => "{$prefix}{$tagNames}",
                'type' => ContactBehaviorTypeConstants::CHANGE_TAG,
                'created_at' => $now,
            ];
        }

        ChContactBehaviorLog::insert($logData);
    }

}